package com.hongyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hongyi.common.framework.constant.Constants;
import com.hongyi.common.framework.constant.UserConstans;
import com.hongyi.common.framework.exception.ServiceException;
import com.hongyi.common.framework.utils.bean.MapstructUtils;
import com.hongyi.common.framework.utils.common.CollectionUtils;
import com.hongyi.common.framework.utils.string.ConvertUtils;
import com.hongyi.common.framework.utils.string.StringUtils;
import com.hongyi.common.mybatis.utils.DateBaseUtils;
import com.hongyi.system.domain.SysDept;
import com.hongyi.system.domain.SysRole;
import com.hongyi.system.domain.SysUser;
import com.hongyi.system.domain.TreeSelect;
import com.hongyi.system.domain.dto.SysDeptDto;
import com.hongyi.system.domain.vo.SysDeptVo;
import com.hongyi.system.mapper.SysDeptMapper;
import com.hongyi.system.mapper.SysRoleMapper;
import com.hongyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.hongyi.system.service.ISysDeptService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysDeptServiceImpl implements ISysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    private LambdaQueryWrapper<SysDept> buildQueryWrapper(SysDeptDto sysDeptDto){
        LambdaQueryWrapper<SysDept> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysDept::getDeleted, Constants.DELETE_NO);
        lqw.eq(ObjectUtils.isNotNull(sysDeptDto.getDeptId()), SysDept::getDeptId, sysDeptDto.getDeptId());
        lqw.eq(ObjectUtils.isNotNull(sysDeptDto.getParentId()), SysDept::getParentId, sysDeptDto.getParentId());
        lqw.like(StringUtils.isNotBlank(sysDeptDto.getDeptName()), SysDept::getDeptName, sysDeptDto.getDeptName());
        lqw.eq(StringUtils.isNotBlank(sysDeptDto.getStatus()), SysDept::getStatus, sysDeptDto.getStatus());
        lqw.orderByAsc(SysDept::getParentId);
        lqw.orderByAsc(SysDept::getOrderNum);
        lqw.orderByAsc(SysDept::getDeptId);
        return lqw;
    }

    /**
     * 查询部门管理数据
     *
     * @param sysDeptDto
     * @return 部门信息集合
     */
    @Override
    public List<SysDeptVo> selectDeptList(SysDeptDto sysDeptDto){
        LambdaQueryWrapper<SysDept> lqw = buildQueryWrapper(sysDeptDto);
        return sysDeptMapper.selectDeptList(lqw);
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    @Transactional
    public List<Integer> selectDeptListByRoleId(Long roleId) {
        SysRole role = sysRoleMapper.selectById(roleId);
        return sysDeptMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDeptVo selectDeptById(Long deptId) {
        SysDeptVo dept = sysDeptMapper.selectVoById(deptId);
        if (ObjectUtils.isNull(dept)) {
            return null;
        }
        SysDeptVo parentDept = sysDeptMapper.selectVoOne(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getDeptName).eq(SysDept::getDeptId, dept.getParentId()));
        dept.setParentName(ObjectUtils.isNotNull(parentDept) ? parentDept.getDeptName() : null);
        return dept;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param deptList 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDeptVo> deptList) {
        List<SysDept> depts = MapstructUtils.convert(deptList, SysDept.class);
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<>();
        List<Long> tempList = new ArrayList<>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<SysDept> iterator = depts.iterator(); iterator.hasNext(); ) {
            SysDept dept = iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param sysDeptDto 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDeptDto sysDeptDto) {
        boolean exist = sysDeptMapper.exists(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getDeptName, sysDeptDto.getDeptName())
                .eq(SysDept::getParentId, sysDeptDto.getParentId())
                .ne(ObjectUtils.isNotNull(sysDeptDto.getDeptId()), SysDept::getDeptId, sysDeptDto.getDeptId()));
        if(exist){
            return UserConstans.NOT_UNIQUE;
        }
        return UserConstans.UNIQUE;
    }

    /**
     * 根据ID查询所有子部门数（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public long selectNormalChildrenDeptById(Long deptId) {
        return sysDeptMapper.selectCount(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getStatus, UserConstans.DEPT_NORMAL)
                .apply(DateBaseUtils.findInSet(deptId, "ancestors")));
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public Boolean hasChildByDeptId(Long deptId) {
        return sysDeptMapper.exists(new LambdaQueryWrapper<SysDept>()
                .eq(SysDept::getParentId, deptId));
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public Boolean checkDeptExistUser(Long deptId) {
        return sysUserMapper.exists(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getDeptId, deptId));
    }

    @Override
    public int insertDept(SysDeptDto sysDeptDto) {
        SysDept info = sysDeptMapper.selectById(sysDeptDto.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstans.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        SysDept dept = MapstructUtils.convert(sysDeptDto, SysDept.class);
        Objects.requireNonNull(dept).setAncestors(info.getAncestors() + StringUtils.COMMA_SEPARATOR + dept.getParentId());
        return sysDeptMapper.insert(dept);
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext()) {
            SysDept n = it.next();
            if (ObjectUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return !getChildList(list, t).isEmpty();
    }


    /**
     * 修改保存部门信息
     *
     * @param sysDeptDto 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDeptDto sysDeptDto) {
        SysDept dept = MapstructUtils.convert(sysDeptDto, SysDept.class);
        SysDept oldDept = sysDeptMapper.selectById(Objects.requireNonNull(dept).getDeptId());
        if (!oldDept.getParentId().equals(dept.getParentId())) {
            SysDept newParentDept = sysDeptMapper.selectById(dept.getParentId());
            if (ObjectUtils.isNotNull(newParentDept) && ObjectUtils.isNotNull(oldDept)) {
                String newAncestors = newParentDept.getAncestors() + StringUtils.SEPARATOR + newParentDept.getDeptId();
                String oldAncestors = oldDept.getAncestors();
                dept.setAncestors(newAncestors);
                updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
            }
        }
        int result = sysDeptMapper.updateById(dept);
        if (UserConstans.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals(UserConstans.DEPT_NORMAL, dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        return sysDeptMapper.deleteById(deptId) ;
    }

    /**
     * 修改子元素关系
     *
     * <p> 将子部门的ancestors字段中旧的祖先路径替换为新的祖先路径 </p>
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = sysDeptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                //应用一个自定义的SQL片段，该片段使用find_in_set函数查找ancestors字段中包含deptId的所有记录。这通常用于MySQL数据库，find_in_set函数用于检查逗号分隔的字符串中是否包含某个值。
                .apply(DateBaseUtils.findInSet(deptId, "ancestors")));
        List<SysDept> list = new ArrayList<>();
        for (SysDept child : children) {
            SysDept dept = new SysDept();
            dept.setDeptId(child.getDeptId());
            dept.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            list.add(dept);
        }
        if (CollectionUtils.isNotEmpty(list)) {
            sysDeptMapper.updateBatchById(list);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = ConvertUtils.toLongArray(ancestors);
        sysDeptMapper.update(null, new LambdaUpdateWrapper<SysDept>()
                .set(SysDept::getStatus, UserConstans.DEPT_NORMAL)
                .in(SysDept::getDeptId, Arrays.asList(deptIds)));
    }

}
